﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data;
using System.Data.OleDb;
using libConn;

namespace ApartmentSale
{
	public partial class AffirmanceEdit : Window
	{
		public AffirmanceEdit()
		{
			this.InitializeComponent();

            gData = new AffirmanceView();
            receipt = new ReceiptView();
            opCommand = OpCommand.CREATE;
		}

        public AffirmanceEdit(AffirmanceView data)
            : this()
        {
            this.Title = "Affirmance Editor";
            gData = data;
            opCommand = OpCommand.UPDATE;

            tbReceiptCode.IsEnabled = false;

            if (data.affirmance_status != 1)
                cbStatus.IsEnabled = true;
            else
            {
                tbReceiptCode.IsEnabled = false;
                cbRule.IsEnabled = false;
            }

            tbReceiptCode.Text = data.receipt_code;
            cbStatus.SelectedIndex = data.affirmance_status;

            tbName.Text = data.affirmance_custom_name;
            tbContact.Text = data.affirmance_custom_contact;

            getReceipt();

            tbCash.Text = String.Format("{0:N2}",receipt.receipt_cash_amount);
            tbCard.Text =  String.Format("{0:N2}",receipt.receipt_card_amount);
            tbCheck.Text =  String.Format("{0:N2}",receipt.receipt_check_amount);
            tbAmount.Text =  String.Format("{0:N2}",receipt.receipt_amount);
        }

        private AffirmanceView gData;
        private ReceiptView receipt;
        private enum OpCommand { CREATE,UPDATE }
        private OpCommand opCommand;

        private bool getRuleData()
        {
            string errMessage = null;
            string str = "Select * From affirmance_rules";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "An error occurred while reading the rules of affirmance.",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false; ;
            }

            foreach (DataRow r in oleDT.Rows)
            {
                cbRule.Items.Add(new AffirmanceRuleView()
                {
                    ID = Convert.ToInt32(r[0]),
                    AffirmanceRuleType = r[1].ToString().Replace("''", "'"),
                    AffirmanceRuleAmount = Convert.ToDouble(r[2]),
                    AffirmanceRuleRule = Convert.ToDouble(r[3])
                });
            }

            if (cbRule.Items.Count > 0)
                cbRule.SelectedIndex = 0;

            return true;
        }

        private bool checkReceiptCode(string data)
        {
            string errMessage = null;
            string str = "SELECT * FROM receipt WHERE receipt_code = '"
                + data.Replace("'", "''") + "'";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Check the receipt SN failed.",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false;
            }

            if (oleDT.Rows.Count > 0)
            {
                System.Windows.MessageBox.Show(
                    "Exist in the same receipt SN, please check.",
                    "Save failed",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Stop);
                return false;
            }

            return true;
        }

        private int getReceiptId(string code)
        {
            string errMessage = null;
            string str = "SELECT * FROM receipt WHERE receipt_code = '"
                + code.Replace("'", "''") + "'";

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Failure to obtain a receipt SN",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return -1;
            }

            if (oleDT.Rows.Count == 0)
            {
                System.Windows.MessageBox.Show(
                    "Can not find the receipt SN.",
                    "Save failed",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Stop);
                return -1;
            }

            return Convert.ToInt32(oleDT.Rows[0][0]);
        }

        private void getReceipt()
        {
            string errMessage = null;
            string str = "SELECT * FROM receipt WHERE receipt_id = "
                + gData.receipt_id;

            DataTable oleDT;
            oleDT = libConn.AccdbConn.query(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Failure to obtain a receipt SN",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return;
            }

            if (oleDT.Rows.Count == 0)
            {
                System.Windows.MessageBox.Show(
                    "Can not find the receipt.",
                    "Save failed",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Stop);
                return;
            }

            DataRow r = oleDT.Rows[0];
            receipt = new ReceiptView(r);
        }

        private bool insertData(AffirmanceView data)
        {
            string errMessage = null;

            string str = "INSERT INTO affirmance (affirmance_status, receipt_id,receipt_code, affirmance_amount, affirmance_rule_type, affirmance_rule_rebate_amount, affirmance_custom_name, affirmance_custom_contact, affirmance_create_date) VALUES (";
            str += data.affirmance_status + ", ";
            str += data.receipt_id + ", '";
            str += data.receipt_code.Replace("'", "''") + "', ";
            str += data.affirmance_amount + ",'";
            str += data.affirmance_rule_type.Replace("'", "''") + "', ";
            str += data.affirmance_rule_rebate_amount + ", '";
            str += data.affirmance_custom_name.Replace("'", "''") + "', '";
            str += data.affirmance_custom_contact.Replace("'", "''") + "', '";
            str += DateTime.Now.ToString() + "')";

            libConn.AccdbConn.exec(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Save data failed affirmance.",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false;
            }

            MessageBox.Show("Add affirmance successes.");
            return true;
        }

        private bool updateData(AffirmanceView data)
        {
            string errMessage = null;

            string str = "UPDATE affirmance SET affirmance_status = " + data.affirmance_status + ", ";
            str += "receipt_code = '" + data.receipt_code + "', ";
            str += "affirmance_amount = " + data.affirmance_amount + ", ";
            str += "affirmance_rule_type = '" + data.affirmance_rule_type.Replace("'", "''") + "', ";
            str += "affirmance_rule_rebate_amount = " + data.affirmance_rule_rebate_amount + ", ";
            str += "affirmance_custom_name = '" + data.affirmance_custom_name.Replace("'", "''") + "', ";
            str += "affirmance_custom_contact = '" + data.affirmance_custom_contact.Replace("'", "''") + "', ";
            str += "affirmance_modify_date = '" + DateTime.Now.ToString() + "' ";
            str += "WHERE affirmance_id = " + data.affirmance_id;

            libConn.AccdbConn.exec(str, ref errMessage);

            if (errMessage != null)
            {
                System.Windows.MessageBox.Show(
                    errMessage,
                    "Affirmance to modify the data failed.",
                    System.Windows.MessageBoxButton.OK,
                    System.Windows.MessageBoxImage.Error);
                return false;
            }
            MessageBox.Show("Affirmance to modify the data successfully.");
            return true;
        }

        private void btSave_Click(object sender, RoutedEventArgs e)
        {
            if (tbReceiptCode.Text.Length == 0)
            {
                MessageBox.Show("Please enter the receipt SN.");
                tbReceiptCode.Focus();
                return;
            }

            receipt.receipt_code = tbReceiptCode.Text;
            gData.receipt_code = tbReceiptCode.Text;

            if (gData.affirmance_status != 1 && cbStatus.SelectedIndex == 1)
            {
                MessageBox.Show("The state can not be manually changed to 'Cancel Out'.");
                cbStatus.SelectedIndex = gData.affirmance_status;
                cbStatus.Focus();
                return;
            }

            gData.affirmance_status = cbStatus.SelectedIndex;

            receipt.receipt_status = cbStatus.SelectedIndex;

            if (cbRule.SelectedIndex == -1)
            {
                MessageBox.Show("Please select the Type.");
                cbRule.Focus();
                return;
            }

            gData.affirmance_rule_type = ((AffirmanceRuleView)cbRule.SelectedItem).AffirmanceRuleType;

            gData.affirmance_rule_rebate_amount = 
                ((AffirmanceRuleView)cbRule.SelectedItem).AffirmanceRuleAmount *
                (((AffirmanceRuleView)cbRule.SelectedItem).AffirmanceRuleRule - 1);

            gData.affirmance_amount = receipt.receipt_amount;
            gData.affirmance_custom_name = tbName.Text;
            gData.affirmance_custom_contact = tbContact.Text;
            receipt.receipt_custom_name = tbName.Text;
            

            if (opCommand == OpCommand.CREATE)
            {
                if (!checkReceiptCode(gData.receipt_code))
                    return;

                string errMessage;
                errMessage = receipt.Insert();

                if (errMessage != "")
                {
                    MessageBox.Show(errMessage, "Save faild", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                gData.receipt_id = getReceiptId(gData.receipt_code);
                if (gData.receipt_id == -1)
                    return;

                if (insertData(gData))
                    this.Close();
            }
            else
            {
                string errMessage;
                errMessage = receipt.Update();

                if (errMessage != "")
                {
                    MessageBox.Show(errMessage, "Save faild", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                if (updateData(gData))
                    this.Close();
            }
        }

        private void btClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            if (!getRuleData())
                this.Close();

            if (opCommand == OpCommand.UPDATE)
            {
                foreach (AffirmanceRuleView rule in cbRule.Items)
                {
                    if (rule.AffirmanceRuleType == gData.affirmance_rule_type)
                    {
                        cbRule.SelectedItem = rule;
                        break;
                    }
                }
            }
        }

        private void AmountChanged(object sender, RoutedEventArgs e)
        {
            double d;
            TextBox c = sender as TextBox;
            if (c != null)
            {
                if (!Double.TryParse(c.Text, out d))
                {
                    c.Text = "0.00";
                }
                else
                {
                    c.Text = String.Format("{0:N2}", d);
                }
            }
            else
            {
                return;
            }

            double cash;
            double card;
            double check;

            if (Double.TryParse(tbCash.Text, out cash) &&
                Double.TryParse(tbCard.Text, out card) &&
                Double.TryParse(tbCheck.Text, out check))
            {
                receipt.receipt_cash_amount = cash;
                receipt.receipt_card_amount = card;
                receipt.receipt_check_amount = check;
                receipt.receipt_amount = cash + card + check;

                tbAmount.Text = String.Format("{0:N2}", receipt.receipt_amount);
            }
        }

	}
}